<?php

/**
 * @file: models/crud_model.php
 *
 * @author roman
 */
class Crud extends CI_Model{
    
    public $table = 'table'; /* THIS PROPERTY MUST BE SET TO YOUR TABLE NAME  */
    public $fields = array();
    public $primary;
    
    public function __construct() {
        parent::__construct();
        $this->fields = $this->get_fields();
        $this->get_primary();
    }
    
    /**
     * @Function: read
     * @Purpose:
     *  Get the array of results and fields by create or update
     * 
     * @return array of results
     */
    public function read($id = NULL){
        if(isset($id)){
            $data['results'] = $this->db->where('id',$id)->get($this->table)->result();
            $data['fields'] = $this->fields;
        } else {
            $data['results'] = $this->db->get($this->table)->result();
            $data['fields'] = $this->fields;
        }
        return $data;
    }
    
    public function create(){
        $data = array();
        foreach ($this->fields as $field){
            $data[$field] = $this->input->post($field);
        }
        $this->db->insert($this->table, $data);
        redirect('upuz/read');
    }
    
    public function update(){
        $data = array();
        $this->db->where($this->primary,  $this->input->post($this->primary));
        foreach($this->fields as $field){
            $data[$field] = $this->input->post($field);
        }
        if($this->db->update($this->table,$data)){
            redirect('upuz');
        }
    }
    
    public function delete(){
        $id = $this->uri->segment(3);
        $this->db->where('id', $id)->delete($this->table);
        redirect('upuz/read');
    }
    
    public function get_fields(){
        return $this->fields = $this->db->list_fields($this->table);
    }
    
    //Get primary key in specific table
    public function get_primary(){
        $fields = $this->db->field_data($this->table);
        foreach ($fields as $field){
            if($field->primary_key == 1){
                $this->primary = $field->name;
            }
        }
    }
    
    //Get type of the field in DB
    //Return example: int, varchar, text,...
    public function get_type($field){
        return $field->type;
    }
    
    public function assemble_form(){
        
    }
}
